/*
 * 文件名：SueLawcaseController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月31日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.la.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.la.domain.SueLawcaseAssist;
import top.infopub.mgr.la.domain.SueLawcaseDomain;
import top.infopub.mgr.la.service.SueLawcaseService;
import top.infopub.mgr.la.vo.SueLawcaseVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.la.SueLawcaseAtt;
import top.infopub.model.la.SueLawcaseProof;
import top.infopub.model.la.SueLawcaseProofAtt;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 起诉案件申请
 * @author WuZhiyang
 * @version 2020年3月31日
 * @see SueLawcaseController
 * @since
 */
@Controller
@RequestMapping("/sueLawcase")
public class SueLawcaseController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private SueLawcaseService sueLawcaseService;

    /**
     * 起诉案件申请
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "la/lay-sueLawcase-list";
    }

    /**
     * 起诉案件申请列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<SueLawcaseDomain> queryDataByCondition(SueLawcaseVo sueLawcaseVo,
                                                        ParamPage paramPage) {
        Page<SueLawcaseDomain> page = new Page<SueLawcaseDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (sueLawcaseVo.getEndDate() != null) {
            sueLawcaseVo.setEndDate(DateUtils.addDays(sueLawcaseVo.getEndDate(), 1));
        }
        //查询时，立案结束日期增加一天
        if (sueLawcaseVo.getSetEndDate() != null) {
            sueLawcaseVo.setSetEndDate(DateUtils.addDays(sueLawcaseVo.getSetEndDate(), 1));
        }
        page = sueLawcaseService.selectByDomainWhere(page, sueLawcaseVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 起诉案件申请-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<SueLawcaseDomain> queryMyCheckDataByCondition(SueLawcaseVo sueLawcaseVo,
                                                               ParamPage paramPage) {
        Page<SueLawcaseDomain> page = new Page<SueLawcaseDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (sueLawcaseVo.getEndDate() != null) {
            sueLawcaseVo.setEndDate(DateUtils.addDays(sueLawcaseVo.getEndDate(), 1));
        }
        //查询时，立案结束日期增加一天
        if (sueLawcaseVo.getSetEndDate() != null) {
            sueLawcaseVo.setSetEndDate(DateUtils.addDays(sueLawcaseVo.getSetEndDate(), 1));
        }
        sueLawcaseVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = sueLawcaseService.selectMyCheckByDomainWhere(page, sueLawcaseVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 起诉案件申请-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        return "la/lay-sueLawcase-add";
    }

    /**
     * 根据id查询起诉案件申请详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 起诉案件申请Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        SueLawcaseVo sueLawcaseVo = sueLawcaseService.queryById(id);
        request.setAttribute("modelDetail", sueLawcaseVo);
        map.put("sueLawcaseVo", sueLawcaseVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, sueLawcaseVo.getProcessId());
        return new ModelAndView("la/lay-sueLawcase-detail", map);
    }

    /**
     * 新增起诉案件申请
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(SueLawcaseAssist sueLawcaseAssist) {

        //判断起诉案件名称是否存在
        int countLawcaseName = sueLawcaseService.countLawcaseName(sueLawcaseAssist.getLawcaseName());
        if (countLawcaseName > 0) {
            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("起诉案件名称【"
                                                            + sueLawcaseAssist.getLawcaseName()
                                                            + "】已经存在~");
        }
        if (sueLawcaseAssist.getFileAtts1() == null || sueLawcaseAssist.getFileAtts1().length < 1) {
            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("起诉状未上传");
        }
        //起诉案件申请表处理
        sueLawcaseAssist.setHrDeptId(sueLawcaseAssist.getHrDeptid());
        sueLawcaseAssist.setHrOrgId(sueLawcaseAssist.getHrOrgid());
        sueLawcaseAssist.setHrStaffApplyId(sueLawcaseAssist.getHrStaffApplyid());
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        sueLawcaseAssist.setId(id);
        sueLawcaseAssist.setAddBy(vo.getId());
        sueLawcaseAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("la_sue_lawcase");
        sueLawcaseAssist.setCodes(code);
        // 处理processId
        sueLawcaseAssist.setProcessId(IdFactory.getUUIDUpper());
        sueLawcaseAssist.setProcessStatus("1");//审批中
        sueLawcaseAssist.setUptBy(vo.getId());
        sueLawcaseAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //证据清单表
        List<SueLawcaseProof> sueLawcaseProofs = new ArrayList<SueLawcaseProof>();
        //上传附件
        List<SueLawcaseProofAtt> sueLawcaseProofAtts = new ArrayList<SueLawcaseProofAtt>();
        String[] proofShowIdx = sueLawcaseAssist.getProofShowIdx();
        if (proofShowIdx != null && proofShowIdx.length > 0) {
            for (int i = 0; i < proofShowIdx.length; i++ ) {
                String showIdx = proofShowIdx[i];
                String proofName = sueLawcaseAssist.getProofName()[i];
                String proofTarget = sueLawcaseAssist.getProofTarget()[i];
                String proofAttribute = sueLawcaseAssist.getProofAttribute()[i];
                String numOfPage = sueLawcaseAssist.getProofNumOfPage()[i];
                //String itemMemo = sueLawcaseAssist.getProofItemMemo()[i];
                SueLawcaseProof sueLawcaseProof = new SueLawcaseProof();
                String sueLawcaseProofId = IdFactory.getUUIDUpper();
                sueLawcaseProof.setSueLawcaseId(id);
                sueLawcaseProof.setId(sueLawcaseProofId);
                sueLawcaseProof.setShowIdx(Integer.parseInt(showIdx));
                sueLawcaseProof.setProofName(proofName);
                sueLawcaseProof.setProofTarget(proofTarget);
                sueLawcaseProof.setProofAttribute(proofAttribute);
                sueLawcaseProof.setNumOfPage(Integer.parseInt(numOfPage));
                //sueLawcaseProof.setItemMemo(itemMemo);
                sueLawcaseProof.setAddBy(vo.getId());
                sueLawcaseProof.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                sueLawcaseProofs.add(sueLawcaseProof);
            }

            String[] proofFileAtts = sueLawcaseAssist.getProofFileAtts();
            String[] showIdxAtt = sueLawcaseAssist.getShowIdxAtt();
            if (proofFileAtts != null) {
                for (int i = 0; i < proofFileAtts.length; i++ ) {
                    SueLawcaseProofAtt sueLawcaseProofAtt = createFileAttProof(vo,
                        proofFileAtts[i]);
                    String showIdx = showIdxAtt[i];
                    sueLawcaseProofAtt.setProofId(showIdx);
                    sueLawcaseProofAtts.add(sueLawcaseProofAtt);
                }
            }

            for (SueLawcaseProofAtt sueLawcaseProofAtt : sueLawcaseProofAtts) {
                for (SueLawcaseProof sueLawcaseProof : sueLawcaseProofs) {
                    if (sueLawcaseProofAtt.getProofId().equals(
                        String.valueOf(sueLawcaseProof.getShowIdx()))) {
                        sueLawcaseProofAtt.setProofId(sueLawcaseProof.getId());
                        break;
                    }
                }
            }
        }

        //上传附件
        List<SueLawcaseAtt> sueLawcaseAtts = new ArrayList<SueLawcaseAtt>();
        String[] fileAtts1 = sueLawcaseAssist.getFileAtts1();
        //附件材料
        if (fileAtts1 != null) {
            for (String file : fileAtts1) {
                SueLawcaseAtt sueLawcaseAtt = createFileAtt(vo, id, file);
                sueLawcaseAtt.setTypes("1");
                sueLawcaseAtts.add(sueLawcaseAtt);
            }
        }

        String[] fileAtts2 = sueLawcaseAssist.getFileAtts2();
        //附件材料
        if (fileAtts2 != null) {
            for (String file : fileAtts2) {
                SueLawcaseAtt sueLawcaseAtt = createFileAtt(vo, id, file);
                sueLawcaseAtt.setTypes("2");
                sueLawcaseAtts.add(sueLawcaseAtt);
            }
        }

        sueLawcaseService.saveSueLawcase(sueLawcaseAssist, sueLawcaseAtts, sueLawcaseProofs,
            sueLawcaseProofAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "法务管理 -起诉案件申请单：立案名称="
                                                              + sueLawcaseAssist.getLawcaseName(),
            null);
        return RspVo.getSuccessResponse();
    }

    private SueLawcaseAtt createFileAtt(AuthorizationVO vo, String sueLawcaseId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        SueLawcaseAtt fileAtt = new SueLawcaseAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setSueLawcaseId(sueLawcaseId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    private SueLawcaseProofAtt createFileAttProof(AuthorizationVO vo, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        SueLawcaseProofAtt fileAtt = new SueLawcaseProofAtt();
        fileAtt.setId(fileAttStr[2]);
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "sueLawcaseAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}